'use client';

import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { useSocket } from '@/hooks/use-socket';
import { useLocalStorage } from '@/hooks/use-local-storage';
import { useAuth } from '@/hooks/use-auth';
import { toast } from '@/components/ui/use-toast';

// 协作上下文类型
interface CollaborationContextType {
  projectId: string;
  documentId: string;
  isConnected: boolean;
  user: { id: string; name: string; email?: string; image?: string } | null;
  activeUsers: Array<{
    id: string;
    name: string;
    status: 'online' | 'idle' | 'offline';
    lastActive?: Date;
  }>;
  saveContent: (content: any) => Promise<boolean>;
  getAutoSavedContent: () => any | null;
}

// 创建协作上下文
const CollaborationContext = createContext<CollaborationContextType | undefined>(undefined);

// 协作提供者组件属性
interface CollaborationProviderProps {
  children: React.ReactNode;
  projectId: string;
  documentId: string;
  className?: string;
}

// 协作提供者组件
export const CollaborationProvider: React.FC<CollaborationProviderProps> = ({
  children,
  projectId,
  documentId,
  className
}) => {
  const { isConnected, socket } = useSocket();
  const { user } = useAuth();
  const [activeUsers, setActiveUsers] = useState<Array<{
    id: string;
    name: string;
    status: 'online' | 'idle' | 'offline';
    lastActive?: Date;
  }>>([]);
  
  // 添加自动保存功能
  const autoSaveKey = `autosave_${projectId}_${documentId}`;
  const [autoSavedContent, setAutoSavedContent, removeAutoSavedContent] = useLocalStorage<{
    content: any;
    timestamp: number;
  } | null>(autoSaveKey, null);
  
  // 保存内容到本地和服务器
  const saveContent = useCallback(async (content: any): Promise<boolean> => {
    try {
      // 保存到本地存储
      setAutoSavedContent({
        content,
          timestamp: Date.now()
      });
      
      // 如果需要，可以在这里添加保存到服务器的逻辑
      
      return true;
    } catch (error) {
      console.error('保存协作内容失败:', error);
      return false;
    }
  }, [setAutoSavedContent]);
  
  // 获取自动保存的内容
  const getAutoSavedContent = useCallback(() => {
    return autoSavedContent?.content || null;
  }, [autoSavedContent]);
  
  // 定期自动保存（每30秒）
  useEffect(() => {
    const autoSaveInterval = setInterval(() => {
      // 这里可以添加获取当前编辑器内容的逻辑
      // 然后调用saveContent保存
      // 由于这里无法直接访问编辑器内容，所以这个功能需要在使用时通过saveContent手动调用
    }, 30000);
    
    return () => {
      clearInterval(autoSaveInterval);
    };
  }, [saveContent]);
  
  // 加入项目
  useEffect(() => {
    if (isConnected && socket) {
      socket.joinProject(projectId);
      
      // 监听用户加入项目
      const handleUserJoined = (data: any) => {
        if (data.projectId === projectId) {
          setActiveUsers((prev) => {
            const existingUser = prev.find(user => user.id === data.user.id);
            if (existingUser) {
              return prev.map(user => 
                user.id === data.user.id 
                  ? { ...user, status: 'online', lastActive: new Date() }
                  : user
              );
          } else {
              return [...prev, { 
                id: data.user.id, 
                name: data.user.name, 
                status: 'online',
                lastActive: new Date()
              }];
            }
          });
        }
      };
      
      // 监听用户离开项目
      const handleUserLeft = (data: any) => {
        if (data.projectId === projectId) {
          setActiveUsers((prev) => 
            prev.map(user => 
              user.id === data.user.id 
                ? { ...user, status: 'offline', lastActive: new Date() }
                : user
            )
          );
        }
      };
      
      // 监听用户状态变化
      const handleUserStatus = (data: any) => {
        if (data.projectId === projectId) {
          setActiveUsers((prev) => 
            prev.map(user => 
              user.id === data.user.id 
                ? { ...user, status: data.status, lastActive: new Date() }
                : user
            )
          );
        }
      };
      
      socket.on('user_joined_project', handleUserJoined);
      socket.on('user_left_project', handleUserLeft);
      socket.on('user_status_changed', handleUserStatus);
      
      return () => {
        socket.off('user_joined_project', handleUserJoined);
        socket.off('user_left_project', handleUserLeft);
        socket.off('user_status_changed', handleUserStatus);
        socket.leaveProject(projectId);
      };
    }
  }, [isConnected, socket, projectId]);

  return (
    <CollaborationContext.Provider value={{
      projectId,
      documentId,
      isConnected,
      user,
      activeUsers,
      saveContent,
      getAutoSavedContent
    }}>
      <div className={className}>
      {children}
      </div>
    </CollaborationContext.Provider>
  );
};

// 协作钩子
export const useCollaboration = () => {
  const context = useContext(CollaborationContext);
  
  if (!context) {
    throw new Error('useCollaboration must be used within a CollaborationProvider');
  }
  
  return context;
}; 